﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmallJob.Services.Interfaces;
using SmallJob.Data;
using SmallJob.Model;
using SmallJob.Data.Interfaces;

namespace SmallJob.Services.Implements
{
    public class CategoryService : RepositoryBase<Category>, ICategoryService
    {
        public CategoryService(IDatabaseFactory DbFactory)
            : base(DbFactory)
        { }
        public List<Category> GetByPage(int page, int pagesize, out int total)
        {
            var list = from u in SmallJobDB.Categories
                       orderby u.ID descending
                       select u;
            int skip = (page - 1) * pagesize;
            total = list.ToList().Count;
            return list.Skip(skip).Take(pagesize).ToList();
        }
        public List<Category> GetAllAvaiable()
        {
            return (from c in SmallJobDB.Categories
                    where c.IsDeleted == false
                    select c).ToList();
        }
        public List<Category> GetTreeCategoryUse()
        {
            var lstRoot = (from c in SmallJobDB.Categories
                           where c.IsDeleted == false && c.ParentID == 0
                           orderby c.DisplayNumber ascending
                           select c).ToList();
            foreach (var item in lstRoot)
            {
                LoadChildAvailable(item);
            }
            return lstRoot;
        }
        public Category LoadChildAvailable(Category category)
        {
            category.Childrens = (from c in SmallJobDB.Categories
                                  where c.IsDeleted == false && c.ParentID == category.ID
                                  orderby c.DisplayNumber ascending
                                  select c).ToList();
            if (category.Childrens != null && category.Childrens.Count > 0)
            {
                foreach (var item in category.Childrens)
                {
                    LoadChildAvailable(item);
                }
            }
            return category;
        }


        public List<Category> GetByPageFilter(int page, int pagesize, out int total, string filter)
        {
            int skip = (page - 1) * pagesize;
            var list = (from d in SmallJobDB.Categories
                        where d.Name.Contains(filter) || d.CreatedBy.Contains(filter)
                        orderby d.ID descending
                        select d);

            total = list.ToList().Count;
            var alist = list.ToList();
            return list.Skip(skip).Take(pagesize).ToList();
        }
    }
}
